package servlet.user;

import entity.AdoptAnimal;
import entity.Pet;
import entity.User;

import service.AdoptService;
import service.PetService;

import service.Impl.AdoptServiceImpl;
import service.Impl.PetServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Date;
import java.time.LocalDate;

@WebServlet(urlPatterns = "/user/AdoptAdd")
public class AdoptAddServlet extends HttpServlet {
    private PetService petService = new PetServiceImpl();
    private AdoptService adoptService = new AdoptServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求编码
        req.setCharacterEncoding("UTF-8");
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        String formattedDate = currentDate.toString(); // 格式为 yyyy-MM-dd

        // 获取所有可用宠物
        req.setAttribute("pet", petService.findNoPet());

        // 设置当前日期到请求属性
        req.setAttribute("currentDate", formattedDate);

        // 转发到添加页面
        req.getRequestDispatcher("/user/add.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求编码
        req.setCharacterEncoding("UTF-8");

        // 获取当前会话
        HttpSession session = req.getSession();

        // 获取用户信息（假设用户信息存储在会话中）
        User user = (User) session.getAttribute("user");
        if (user == null) {
            // 如果用户未登录，重定向到登录页面
            resp.sendRedirect(req.getContextPath() + "/user/index");
            return;
        }

        // 获取表单参数
        int userId = user.getId(); // 从会话中获取用户ID
        int petId = Integer.parseInt(req.getParameter("pet"));
        String adoptTimeStr = req.getParameter("adoptTime"); // 日期格式为 yyyy-MM-dd
        String stateStr = req.getParameter("state");

        // 创建 AdoptAnimal 对象
        AdoptAnimal adoptAnimal = new AdoptAnimal();
        User userObj = new User();
        userObj.setId(userId); // 设置用户ID
        adoptAnimal.setUser(userObj);

        Pet pet = new Pet();
        pet.setId(petId);
        adoptAnimal.setPet(pet);

        // 设置状态为 0
        adoptAnimal.setState(0);

        // 设置领养时间
        adoptAnimal.setAdoptTime(Date.valueOf(adoptTimeStr));

        // 保存到数据库
        adoptService.save(adoptAnimal);

        // 重定向到领养列表页面或其他页面
        resp.sendRedirect(req.getContextPath() + "/user/index");
    }
}